package com.changgou.system.filter;

import com.changgou.system.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取 request ,response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.判断该请求是否为登录请求
        if(request.getURI().getPath().contains("/admin/login")){
            //是登录请求, 放行
            return chain.filter(exchange);
        }
        //3.判断该请求头中是否有令牌
        //3.1获取请求头中的令牌
        String token = request.getHeaders().getFirst("token");
        //3.2判断令牌是否为空
        if(StringUtils.isEmpty(token)){
            //令牌为空 , 响应中放入 错误的状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回
            return response.setComplete();
        }
        //4判断该令牌是否非法
        //4.1 使用 JWT工具类解析 令牌,
        try {
            JwtUtil.parseJWT(token);
            //解析没有报错,令牌合理,放行
            return chain.filter(exchange);
        } catch (Exception e) {
            //解析失败 , 响应中放入 错误的状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回
            return response.setComplete();
        }
    }


    //该过滤器 执行优先级 ,返回值越低,优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
